package org.example;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.example.entity.User;
import org.example.mapper.UserMapper;
import org.example.service.UserService;
import org.example.service.impl.UserServiceImpl;

import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

public class NoSpring {

	private static SqlSessionFactory sqlSessionFactory;

	static {
		try {
			InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
			sqlSessionFactory = new MybatisSqlSessionFactoryBuilder().build(inputStream);
		} catch (IOException e) {
			throw new RuntimeException("Failed to initialize SqlSessionFactory", e);
		}
	}

	public static void main(String[] args) {

		// 自动提交
		SqlSession session = sqlSessionFactory.openSession(true);
		UserMapper mapper = session.getMapper(UserMapper.class);

		// 重要：创建UserService，并初始化
		UserService userService = new UserServiceImpl() {{
			this.baseMapper = mapper;
		}};

		User user = new User();
		user.setPassword("123");
		user.setName("lkw");
		boolean saveResult = userService.save(user);
		System.out.println("Save result: " + saveResult);
		System.out.println("Saved user: " + userService.getById(user.getId()));

		// 分页
		Page<User> page = new Page<>(1, 5); // Page 1, 5 records per page
		Page<User> userPage = userService.page(page);
		System.out.println("Total Records: " + userPage.getTotal());
		System.out.println("Records on Page: " + userPage.getRecords());

		session.close();
	}

}